import React from 'react';
import ReactDOM from 'react-dom';

let hookStates = []; // 保存所有状态的数组
let hookIndex = 0; // 默认 从第一个开始保存状态

function useReducer(reducer, initialState) {
  hookStates[hookIndex] = hookStates[hookIndex] || initialState;
  let currentIndex = hookIndex;
  function dispatch(action) {
    // 这里只是基于了一个函数 来实现了状态初始化
    hookStates[currentIndex] = reducer
      ? reducer(hookStates[currentIndex], action)
      : initialState;
    render();
  }
  return [hookStates[hookIndex++], dispatch];
}

// useReducer

function reducer(state, action) {
  // reducer
  switch (action.type) {
    case 'add':
      return state + 1;
    default:
      return state; // 还用来初始化默认状态的
  }
}

function Counter() {
  // useState 和 useReducer
  let [state, dispatch] = useReducer(reducer, 0);

  return (
    <div>
      <span>{state}</span>
      <button onClick={() => dispatch({ type: 'add' })}>+</button>
    </div>
  );
}

function render() {
  hookIndex = 0; // 保证每次渲染的时候 都是从0的开始 进行匹配获取状态
  ReactDOM.render(<Counter />, document.getElementById('root'));
}
render();

// 1) useState 我们将useState的状态 管理到数组里， 将索引和状态关联起来
// 2) 每次更新状态的时候 通过索引获取对应的状态，并进行更新
